package mq

import (
	"time"
	"fmt"
	"gitee.com/thomasgw/rabbitMQ-demo/message"
	"gitee.com/thomasgw/rabbitMQ-demo/util"
	"sync"
)

type Emitter interface{
	Chan() chan message.Message
}

type EventEmitter struct {
	data chan message.Message
	lock *sync.Mutex
}

func NewEventEmitter(ch chan message.Message) *EventEmitter {
	return &EventEmitter{
		data: ch,
		lock: new(sync.Mutex),
	}
}

func(emitter *EventEmitter) Chan() chan message.Message{
	return emitter.data
}

func(emitter *EventEmitter) EmitAdd(x,y int) error {
	fmt.Println("Put value in Emitter -- ADD event.")
	z := x+y
	result := util.IntToBytes(z)
	emitter.lock.Lock()
	emitter.data <- &message.AddMessage{
		Key:     "ADD",
		Time:    time.Now().Nanosecond(),
		Payload: result,
	}
	emitter.lock.Unlock()
	return nil
}

func(emitter *EventEmitter) EmitMinus(x,y int) error {
	fmt.Println("Put value in Emitter -- MINUS event.")
	z := x-y
	if z <0 {
		z = y-x
	}
	result := util.IntToBytes(z)
	emitter.lock.Lock()
	emitter.data <- &message.MinusMessage{
		Key:     "MINUS",
		Time:    time.Now().Nanosecond(),
		Payload: result,
	}
	emitter.lock.Unlock()
	return nil
}
